class GamePiece {
  constructor(width, height, color, x, y, ctx, type) {
    this.width = width;
    this.height = height;
    this.color = color;
    this.x = x;
    this.y = y;
    this.ctx = ctx;
    this.type = type;
    this.gravity = 0.05;
    this.gravitySpeed = 0;
    this.bounce = 0.6;
    this.speedY = 0;
    this.speedX = 0;
    this.draw();
  }

  draw() {
    if (this.type === "text") {
      this.drawText();
    } else {
      this.drawRect();
    }
  }

  drawText() {
    this.ctx.font = this.width + " " + this.height;
    this.ctx.fillStyle = this.color;
    this.ctx.fillText(this.text || "", this.x, this.y);
  }

  drawRect() {
    this.ctx.fillStyle = this.color;
    this.ctx.fillRect(this.x, this.y, this.width, this.height);
  }

  update() {
    this.draw();
  }

  newPos() {
    if (this.type === "rectangle") {
      this.gravitySpeed += this.gravity;
      this.x += this.speedX;
      this.y += this.speedY + this.gravitySpeed;
      this.hitBottom();
    } else {
      this.x += this.speedX;
      this.y += this.speedY;
    }
  }

  hitBottom() {
    const rockbottom = this.ctx.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
      this.gravitySpeed = -(this.gravitySpeed * this.bounce);
    }
  }

  crashWidth(otherPiece) {
    let myLeft = this.x,
      myRight = this.x + this.width,
      myTop = this.y,
      myBottom = this.y + this.height;

    let otherLeft = otherPiece.x,
      otherRight = otherPiece.x + otherPiece.width,
      otherTop = otherPiece.y,
      otherBottom = otherPiece.y + otherPiece.height;

    let crash = true;

    if (
      myRight < otherLeft ||
      otherRight < myLeft ||
      myTop > otherBottom ||
      myBottom < otherTop
    ) {
      crash = false;
    }
    return crash;
  }
}

export default GamePiece;
